package tls;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;

public class RSAExchange {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        KeyPair serverKeyPair = keyGen.generateKeyPair();

        // 2. 客户端生成预主密钥（只需要版本和随机数）
        SecureRandom secureRandom = new SecureRandom();
        byte[] preMasterSecret = generatePreMasterSecretRSA(12, secureRandom);

        // 3. 客户端使用服务器公钥加密
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, serverKeyPair.getPublic());
        byte[] encryptedPreMaster = cipher.doFinal(preMasterSecret);

        // 4. 服务器使用私钥解密
        cipher.init(Cipher.DECRYPT_MODE, serverKeyPair.getPrivate());
        byte[] decryptedPreMaster = cipher.doFinal(encryptedPreMaster);

        System.out.println("Original: " + Hex.encodeHexString(preMasterSecret));
        System.out.println("Decrypted: " + Hex.encodeHexString(decryptedPreMaster));
    }


    public static byte[] generatePreMasterSecretRSA(Integer version, SecureRandom random) {
        byte[] preMasterSecret = new byte[48];

        // 设置TLS版本号（前2字节）
        switch (version) {
            case 12:
                preMasterSecret[0] = 0x03;
                preMasterSecret[1] = 0x03;
                break;
            case 11:
                preMasterSecret[0] = 0x03;
                preMasterSecret[1] = 0x02;
                break;
            // 其他版本...
        }

        // 生成46字节的强随机数
        byte[] randomBytes = new byte[46];
        random.nextBytes(randomBytes);
        System.arraycopy(randomBytes, 0, preMasterSecret, 2, 46);

        return preMasterSecret;
    }
}
